package service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.transform.stream.StreamResult;

import org.jdom.JDOMException;

import entity.SoapuiProject;

public class GeraSoapUIXML {

	public void getMethodXml(SoapuiProject sProject, String caminho) throws JDOMException, IOException {
		ObjectFactory factory = new ObjectFactory(sProject, caminho);
		SoapuiProject soapuiProject = factory.createSoapuiProject();

		System.out.println(new GeraSoapUIXML().marshal(soapuiProject,soapuiProject.getName(),caminho));
		
	}

	public String marshal(Object object,String name, String caminho) throws IOException {
		final StringWriter out = new StringWriter();
		JAXBContext context = null;
		try {
			context = JAXBContext.newInstance(object.getClass());
			Marshaller marshaller = context.createMarshaller();
			File dir = new File(caminho+"/"+name);
			if (dir.mkdir()) {  
			    System.out.println("Diretorio criado com sucesso!");  
			} else {  
			    System.out.println("Erro ao criar diretorio!");  
			}  
			marshaller.marshal(object, new FileWriter(dir+"/"+name+"SOAP"+".xml"));
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(object, new StreamResult(out));
		} catch (PropertyException e) {
			e.printStackTrace();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return out.toString();
	}

}
